import pymysql
import threading

lock = threading.Lock()


class DB:
    def __init__(self):
        self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='5211314cxf', db='social',
                                    charset='utf8', cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    # def reConnect(self):
    #     try:
    #         self.conn.ping()
    #     except:
    #         self.conn()

    # 更新添加
    def update(self, sql):
        self.cursor.execute(sql)
        # self.conn.commit()

    # 获取一条
    def find(self, sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res


    # 获取多条
    """
        lock.acquire()
        cursor.execute(command, data)
        lock.release()

    每个线程拥有自己的数据库连接，即在线程调用函数中加上数据库连接代码
    所有线程共用一个连接池，需要考虑总数和连接池上线的问题    
    """
    def find_all(self, sql):
        # self.reConnect()
        # lock.acquire()
        # self.cursor.execute(sql)
        # res = self.cursor.fetchall()
        # # lock.acquire()
        # # self.cursor.execute(res, sql)
        # lock.release()
        # return res

        # self.reConnect()
        lock.acquire()
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        lock.release()
        return res

    def commit(self):
        self.conn.commit()

    def rollback(self):
        self.conn.rollback()


db1 = DB()
